<template>
    <section>
        <div class="panel">
            <div class="panel-head">
                <strong><i class="el-icon-date"/><span class="title">银行落地页配置</span></strong>
            </div>
            <div class="body-content">
                <!-- 查询条件 -->
                <el-form :inline="true" size='small'>
                    <el-form-item>
                        选择银行:
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="bankId" size='small' @change="selectChange" placeholder="选择银行" style="width: 140px">
                            <el-option v-for="item in banksData" :key="item.autoId" :label="item.bankName" :value="item.autoId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="addeditDailog('add')" size='small'>新增</el-button>
                    </el-form-item>
                </el-form>
                <!-- 数据表格 -->
                <el-table :data="tableData" border v-loading="listLoading" element-loading-text="拼命加载中">
                    <el-table-column label="序号" width="70">
                        <template slot-scope="scope">
                            <el-popover trigger="click" placement="top">
                                <span>autoId: {{ scope.row.autoId }}</span>
                                <div slot="reference">
                                    {{scope.$index + 1}}
                                </div>
                            </el-popover>
                        </template>                    
                    </el-table-column>
                    <el-table-column label="资源位名称" width="120">
                        <template slot-scope="scope">
                            {{positionMap[scope.row.position]}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="sort" label="排序" width="65">
                        <template slot-scope="scope">
                            <span v-show="scope.row.position == 1">{{scope.row.sort}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="图片链接" class-name="classNamebg">
                        <template slot-scope="scope">
                            <img :class="scope.row.position == 2 ? 'img-Bg' : ''" :src="scope.row.imageUrl" alt="图标" style="width: 120px;height: 60px;margin: 0 auto;"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="link" label="跳转链接" width="90">
                        <template slot-scope="scope">
                            <el-popover trigger="hover" placement="top">
                                <div>跳转链接: </div>
                                <span>{{ scope.row.link }}</span>
                                <div slot="reference" class="name-wrapper">
                                    <el-tag size="medium">查看</el-tag>
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column prop="activateTime" label="开始时间" />
                    <el-table-column prop="expireTime" label="结束时间" />
                    <el-table-column label="操作" width="100">
                        <template slot-scope="scope">
                            <!-- 启用禁用不包含 0头图和2分享图 -->
                            <el-button type="text" v-show='scope.row.position == 1' @click="isDisable(scope.row.autoId,scope.row.disabled)">{{scope.row.disabled == 0 ? '禁用':'启用'}}</el-button>
                            <el-button type="text" @click="addeditDailog('edit',scope.row)">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 弹窗 -->
                <el-dialog :title="dialogTitle" :close-on-click-modal='closeOnClickModal' :visible.sync="dialogFormVisible" width="50%" @close="closeDailog" @open="openDailog">
                    <el-form>
                        <el-form-item label="图片位置:" :label-width="formLabelWidth">
                            <el-select v-model="dailogFrom.position" :disabled="selectDisabled" size='small' placeholder="选择位置" style="width: 150px">
                                <el-option v-for="(value,key) in positionMap" :key="key" :label="value" :value="key" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="图片链接:" :label-width="formLabelWidth">
                            <el-input v-model.trim="dailogFrom.imageUrl" style="width:370px;" size="small" />
                            <el-upload :headers="headers" :with-credentials="withCredentials" name="multipartFile" ref="upload" :action="uploadURL" :on-exceed="handleExceed" :on-remove="handleRemove" :on-success='handleSuccess' :file-list="fileList" :limit="1" :before-upload="beforeAvatarUpload">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="跳转链接:" :label-width="formLabelWidth">
                            <el-input v-model.trim="dailogFrom.link" style="width:370px;" size="small" />
                        </el-form-item>
                        <el-form-item label="活动时间:" :label-width="formLabelWidth">
                            <el-date-picker
                                v-model="dateValue"
                                @change="dateChange"
                                type="datetimerange"
                                size="small"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :clearable="timeClearable"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                style="width:370px;"/>
                        </el-form-item>
                        <el-form-item v-show="isSortshow" label="排序:" :label-width="formLabelWidth">
                            <el-input v-model.trim="dailogFrom.sort" style="width:150px;" size="small" />
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="confirm">确 定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </section>
</template>

<script>
import * as api from "../../api/api";
export default {
    data() {
        return {
            closeOnClickModal: false,

            banksData: [], // 银行名称列表
            bankId: "", // 银行ID

            tableData: [], // 数据列表
            listLoading: false,

            // 位置对应信息map
            positionMap: {
                "0": "头图",
                "1": "资源图",
                "2": "分享图"
            },

            dialogTitle: "", // 弹窗标题
            dialogType: "", // 弹窗类型
            dialogFormVisible: false,
            formLabelWidth: "120px",
            dailogFrom: {
                position: "", // 图片位置
                imageUrl: "", //图片链接
                link: "", //跳转链接
                activateTime: "", //开始时间
                expireTime: "", //结束时间
                sort: "" //排序
            },
            // select框禁点
            selectDisabled: false,
            // 排序是否显示
            isSortshow: false,

            // 图片上传
            uploadURL: `${api.baseURL}/uploadFile`,
            headers: {
                token: window.sessionStorage.token
            },
            fileList: [],
            withCredentials: true, // 支持发送 cookie 凭证信息

            // 时间框
            dateValue: "",
            timeClearable: false
        };
    },
    watch: {
        // 监听 图片位置选择 判断排序是否展示
        positionValue(val) {
            // 当位置为1资源图时展示
            if (val == "1") {
                this.isSortshow = true;
            } else {
                this.dailogFrom.sort = ""; // 排序字段清空
                this.isSortshow = false;
            }
        }
    },
    computed: {
        positionValue() {
            return this.dailogFrom.position;
        }
    },
    methods: {
        // 打开弹窗
        openDailog() {
            // 银行名称展示
            const bankName = this.findBankNameByid(this.bankId);
            this.dialogType === "add"
                ? (this.dialogTitle = `新增银行落地页(${bankName})`)
                : (this.dialogTitle = `编辑银行落地页(${bankName})`);
        },
        //根据银行id 查询银行名称
        findBankNameByid(id) {
            let bankName = "";
            this.banksData.forEach(item => {
                if (item.autoId == id) {
                    bankName = item.bankName;
                    return;
                }
            });
            return bankName;
        },
        // 新增/编辑 弹窗
        addeditDailog(type, rowData) {
            if (type == "add") {
                this.dialogType = "add";
            } else {
                this.dialogType = "edit";
                this.selectDisabled = true;
                // this.dailogFrom = Object.assign({}, rowData);
                for (const key in rowData) {
                    this.dailogFrom[key] = rowData[key].toString();
                }
                // 时间反显赋值
                this.dateValue = [
                    this.dailogFrom.activateTime,
                    this.dailogFrom.expireTime
                ];
            }
            this.dialogFormVisible = true;
        },
        // 关闭弹窗 输入框数据清空
        closeDailog() {
            this.dailogFrom = {
                position: "", // 图片位置
                imageUrl: "", //图片链接
                link: "", //跳转链接
                activateTime: "", //开始时间
                expireTime: "", //结束时间
                sort: "" //排序
            };
            // 时间选择框清空
            this.dateValue = [];
            // select框禁点
            this.selectDisabled = false;
        },

        // 启用禁用操作
        isDisable(autoId, status) {
            const statusStr = status === 1 ? "启用" : "禁用";
            this.$confirm(`确定${statusStr}该资源位吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    let disabled = status == 0 ? 1 : 0;
                    api.updateBankList({
                        autoId: autoId,
                        disabled: disabled
                    }).then(() => {
                        // 银行落地页资源列表
                        this.$message.success(`${statusStr}成功!`);
                        this.bankListRecords();
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消"
                    });
                });
        },

        // 文件移除事件
        handleRemove() {
            this.fileList = [];
            this.dailogFrom.imageUrl = "";
        },
        // 超出上传限制提示
        handleExceed() {
            this.$message.warning("当前限制只能上传 1 个文件");
        },
        // 上传成功
        handleSuccess(res) {
            if (res.code === 1) {
                this.$message.success("上传成功！");
                this.dailogFrom.imageUrl = res.data;
            } else {
                this.$message.error(res.message);
                if (res.code === 40100) {
                    this.$router.push({
                        path: "login"
                    });
                }
            }
        },
        // 上传文件格式大小判断
        beforeAvatarUpload(file) {
            const fileName = file.name;
            const index = fileName.lastIndexOf(".");
            const fileFormat = fileName.substring(index + 1, fileName.length);
            const isName =
                fileFormat === "png" ||
                fileFormat === "jpg" ||
                fileFormat === "jpeg";
            const isLt150KB = file.size / 1024 < 150;
            if (!isName) {
                this.$message.error("上传文件只能是 png/jpg/jpeg 格式!");
                this.fileList = [];
            }
            if (!isLt150KB) {
                this.$message.error("上传文件大小不能超过 150KB!");
                this.fileList = [];
            }
            return isName && isLt150KB;
        },

        // 时间change
        dateChange(date) {
            if (date != null) {
                this.dailogFrom.activateTime = date[0];
                this.dailogFrom.expireTime = date[1];
            } else {
                this.dailogFrom.activateTime = "";
                this.dailogFrom.expireTime = "";
            }
        },

        // 新增/编辑 确定
        confirm() {
            if (!this.dailogFrom.position) {
                this.$message.error("请选择图片位置!");
                return false;
            }
            if (!this.dailogFrom.imageUrl) {
                this.$message.error("请上传图片!");
                return false;
            }
            // if (!this.dailogFrom.link) {
            //     this.$message.error("请输入跳转链接!");
            //     return false;
            // }
            if (!this.dailogFrom.activateTime) {
                this.$message.error("请选择生效时间!");
                return false;
            }
            if (this.isSortshow) {
                if (!this.dailogFrom.sort) {
                    this.$message.error("请输入排序!");
                    return false;
                }
                if (
                    isNaN(this.dailogFrom.sort) ||
                    Number(this.dailogFrom.sort) <= 0
                ) {
                    this.$message.error("请输入正确排序!");
                    return false;
                }
            }
            console.log(this.dailogFrom);
            if (this.dialogType === "add") {
                // 添加银行落地页资源位
                this.addBankListFun();
            } else if (this.dialogType === "edit") {
                // 更新银行落地页资源信息
                this.updateBankInfoFun();
            }
        },
        // 下拉框选择事件
        selectChange() {
            // 银行落地页资源列表
            this.bankListRecords();
        },

        // 银行落地页资源列表
        bankListRecords() {
            this.listLoading = true;
            api.getBankListRecords({
                bankId: this.bankId
            }).then(res => {
                this.listLoading = false;
                this.tableData = res.data.list;
            });
        },
        // 获取银行名称列表
        getBankNameList() {
            api.bankNameList().then(res => {
                this.banksData = res.data;
                this.bankId = res.data[0].autoId;
                // 银行落地页资源列表
                this.bankListRecords();
            });
        },
        // 添加银行落地页资源位
        addBankListFun() {
            api.addBankList({
                ...this.dailogFrom,
                bankId: this.bankId
            }).then(() => {
                this.$message.success("新增成功!");
                // 银行落地页资源列表
                this.bankListRecords();
                this.dialogFormVisible = false;
            });
        },
        // 更新银行落地页资源信息
        updateBankInfoFun() {
            api.updateBankList(this.dailogFrom).then(() => {
                this.$message.success("更新成功!");
                // 银行落地页资源列表
                this.bankListRecords();
                this.dialogFormVisible = false;
            });
        }
    },
    mounted() {
        // 获取银行名称列表
        this.getBankNameList();
    }
};
</script>

<style>
.classNamebg .cell .img-Bg {
    background-color: #056bae;
    width: 120px !important;
    height: 30px !important;
}
</style>
